package calculate24.play.SelfCalculate.CardsHistory;

import calculate24.play.common.card.Card;

//保存cards的状态，以便回退到上一步
public class CardsHistory {
    private final VersionList<CardRecord[]> list = new VersionList<CardRecord[]>(4);
    private final Card[] cards;

    public CardsHistory(Card[] cards) {
        this.cards = cards;
        save();
    }

    //保存当前的数据
    public void save() {
        CardRecord[] cardStats = new CardRecord[4];
        for(int i = 0; i < 4; ++i) {
            cardStats[i] = new CardRecord();
            cardStats[i].setStatusFrom(cards[i]);
        }
        if(canForward()) {
            list.fork(cardStats);
            list.rollForward();
        } else {
            list.append(cardStats);
            list.rollForward();
        }
    }

    //回退到上一个版本
    public void back() {
        if(canBack()) {
            list.rollBack();
            CardRecord[] cardStats = list.getCurrentVersion();
            for(int i = 0; i < 4; ++i) {
                cardStats[i].getStatusInto(cards[i]);
            }
        }
    }

    //前进到下一个版本
    public void forward() {
        if(canForward()) {
            list.rollForward();
            CardRecord[] cardStats = list.getCurrentVersion();
            for(int i = 0; i < 4; ++i) {
                cardStats[i].getStatusInto(cards[i]);
            }
        }
    }

    public boolean canBack() {
        return list.canRollBack();
    }

    public boolean canForward() {
        return list.canRollForward();
    }

}


